package com.mind.core.net.websocket.codec;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageEncoder;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;

import java.util.List;

import org.apache.log4j.Logger;

import com.mind.core.net.msg.Message;

public class WebsocketBinaryEncoder extends MessageToMessageEncoder {
	private static final Logger logger = Logger
			.getLogger(WebsocketBinaryEncoder.class);

	@Override
	protected void encode(ChannelHandlerContext ctx, Object msg, List out)
			throws Exception {
		if (msg instanceof DefaultFullHttpResponse) {
			out.add(msg);
			return;
		}
		if (!(msg instanceof Message)) {
			logger.info("This encoder only encode mop's IMessage");
			return;
		}
		Message message = (Message) msg;
		ByteBuf buf = ctx.alloc().buffer(message.getInitBufferLength());
		message.setBuffer(buf);
		if (!message.write()) {
			throw new Exception("encoder  wrong!message code="
					+ message.getMessageType());
		}
		out.add(new BinaryWebSocketFrame(message.getBuffer()));
	}

}
